import uuid

from django.db import models
from django.utils import timezone


class Route(models.Model):
    objects = models.Manager

    id = models.CharField(primary_key=True, default=uuid.uuid4, editable=False, max_length=255)
    # 路由名称
    name = models.CharField(max_length=100, help_text='路由名称')
    # 路径标题
    title = models.CharField(max_length=100, help_text='路径标题')
    # 路由路径
    route = models.CharField(max_length=255, help_text='路由路径')
    # 图标
    icon = models.CharField(max_length=100, null=True, blank=True, help_text='图标')
    # 是否有子路由（叶子节点）
    is_leaf = models.BooleanField(default=False, help_text='是否有子路由')
    # 路由组件名称
    app_url = models.CharField(max_length=100, help_text='路由组件名称')
    # 父路由，根路由的父路由为null
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, related_name='children',
                               help_text='父路由')

    # 排序
    index = models.IntegerField(unique=True, null=True, blank=True, help_text="排序")
    # 创建时间
    create_time = models.DateTimeField(default=timezone.now, help_text='创建时间')
    # 更新时间
    update_time = models.DateTimeField(auto_now=True, help_text='更新时间')

    def __str__(self):
        return self.title

    def get_children(self):
        """ 获取该路由的子路由 """
        return Route.objects.filter(parent=self)

    def save(self, *args, **kwargs):
        if self.index is None:  # 如果没有设置 index，则手动计算并赋值
            max_index = Route.objects.aggregate(models.Max('index'))['index__max']
            if max_index is None:
                self.index = 1  # 如果没有记录，设置为 1
            else:
                self.index = max_index + 1  # 否则设置为最大值 + 1
        super().save(*args, **kwargs)